package com.ruoyi.web.controller.wechat;

import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.wxpay.util.SignUtils;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.mall.service.ChatGPTService;
import com.ruoyi.wechat.domain.WxUser;
import com.ruoyi.wechat.mapper.WeChatLoginUser;
import com.ruoyi.wechat.service.IWxUserService;
import com.swordintent.chatgpt.ChatgptClient;
import com.swordintent.chatgpt.ChatgptClientImpl;
import com.swordintent.chatgpt.protocol.ChatGptConfig;
import com.swordintent.chatgpt.protocol.ChatRequest;
import com.swordintent.chatgpt.protocol.ChatResponse;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author cj
 */
@RestController
@RequestMapping("/wechat")
public class WeChatHelloController {

    @Autowired
    private WxMpService wxService;


    @Autowired
    private ChatGPTService chatGPTService;

    @Autowired
    IWxUserService wxUserService;

    private static Logger log = LoggerFactory.getLogger(WeChatHelloController.class);

    @GetMapping("hello")
    public String hello(){
        return "hello";
    }


    @RequestMapping("/notify")
    @ResponseBody
    public String wechatNotify(@RequestParam(name = "signature", required = false) String signature,
                               @RequestParam(name = "timestamp", required = false) String timestamp,
                               @RequestParam(name = "nonce", required = false) String nonce,
                               @RequestParam(name = "echostr", required = false) String echostr)
    {
        log.info("接收到来自微信服务器的认证消息：[{}, {}, {}, {}]", signature,timestamp, nonce, echostr);
        if (StringUtils.isAnyBlank(signature, timestamp, nonce)) {
            throw new IllegalArgumentException("请求参数非法，请核实!");
        }
        if (wxService.checkSignature(timestamp, nonce, signature)) {
            return echostr;
        }
        return "非法请求";
    }

    @RequestMapping("/userInfo")
    @ResponseBody
    public AjaxResult userInfo(HttpServletRequest request)
    {

        return AjaxResult.success(wxUserService.selectWxUeserByOpenId(((WeChatLoginUser) request.getAttribute("user")).getUser().getOpenId()));

    }

    @PostMapping("/chat")
    @ResponseBody
    public AjaxResult chat(@RequestBody Question question,
                           HttpServletRequest request)
    {
        WxUser user = wxUserService.selectWxUeserByOpenId(((WeChatLoginUser) request.getAttribute("user")).getUser().getOpenId());
        if (user.getBalance()<=0){
            return  new AjaxResult(HttpStatus.MOVED_PERM, "余额不足，请充值");
        }
        List<String> result = chatGPTService.chat(question.getPrompt(), user);
        user.setBalance(user.getBalance()-1);
        wxUserService.updateWxUser(user);
        return AjaxResult.success(result);

    }


//    public static void main(String[] args) {
//
//
//        Map<String, String> params = new HashMap<>();
//        params.put("appId","wxa7b252382189db5f");
//        params.put("timeStamp","1676533132");
//        params.put("nonceStr","abcd");
//        params.put("package","prepay_id=wx16171322355462b79026deee56063c0000");
//        params.put("signType","MD5");
//        System.out.printf(SignUtils.createSign(params,"MD5","8a021b5a00894cbab3c7d9ab293f372d",null));
//    }
}
